import * as React from 'react';
import { Button, Input, message, Select, Table, TreeSelect } from 'antd';
import { ColumnProps } from 'antd/es/table';
import styles from './styles/index.less';
import { getDepartList, OrgNode } from './service';
import { OrgDataItem } from './interface';

export interface OrgTableProps {
  dataSource?: OrgDataItem[];
  onChange?: (data: OrgDataItem[]) => void;
}

export interface OrgTableState {
  departList: OrgNode[];
  dataSource: OrgDataItem[];
  loading: boolean;
}

function shouldUpdateDataSource(data: OrgDataItem[], data2: OrgDataItem[]) {
  if (data.length !== data2.length) {
    return true;
  }
  return JSON.stringify(data) !== JSON.stringify(data2);
}

class OrgTable extends React.Component<OrgTableProps, OrgTableState> {
  public static propTypes = {};
  public static defaultProps = {};

  public constructor(props: Readonly<OrgTableProps>) {
    super(props);
    const { dataSource = [] } = props;
    this.state = {
      loading: false,
      departList: [],
      dataSource: this.getDataSource(dataSource),
    };
  }

  public async componentDidMount() {
    // load departsList
    await this.loadData();
  }

  public componentDidUpdate(prevProps: Readonly<OrgTableProps>) {
    const preDataSource = prevProps.dataSource || [];
    const dataSource = this.props.dataSource || [];
    if (shouldUpdateDataSource(preDataSource, dataSource)) {
      this.setState({ dataSource: this.getDataSource(dataSource) });
    }
  }

  public render() {
    const { departList } = this.state;
    const columns: ColumnProps<OrgDataItem>[] = [
      {
        title: '部门',
        dataIndex: 'department',
        render: (_, record, index) => {
          return (
            <div>
              <TreeSelect
                style={{ width: 140 }}
                value={record.department}
                dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                treeData={departList}
                placeholder="Please select"
                treeDefaultExpandAll
                onChange={(value) => this.handleDepartChange(record, index, value)}
              />
            </div>
          );
        },
      },
      {
        title: '职责',
        dataIndex: 'dbh',
        render: (_, record, index) => {
          return (
            <div>
              <Input.TextArea
                value={record.description}
                placeholder="请输入位置职责信息"
                className={styles.desc}
                onChange={({ target: { value } }) => this.handleDescChange(record, index, value)}
              />
            </div>
          );
        },
      },
      {
        title: '操作',
        dataIndex: '__action',
        render: (_, record, index) => {
          return (
            <div className={styles.action}>
              <div
                className={styles.actionBtn}
                onClick={(e) => {
                  e.stopPropagation();
                  this.handleDelete(record, index);
                }}
              >
                删除
              </div>
              <div
                className={styles.actionBtn}
                onClick={(e) => {
                  e.stopPropagation();
                  this.handleAdd(record, index);
                }}
              >
                添加
              </div>
            </div>
          );
        },
      },
    ];
    const dataSource = this.state.dataSource || [];
    return (
      <div>
        <div>
          {dataSource.length ? (
            <Table
              className={styles.table2}
              pagination={false}
              rowKey={'id'}
              size="middle"
              bordered
              columns={columns}
              dataSource={dataSource || []}
            />
          ) : (
            <Button onClick={() => this.handleAdd(null, 0)}>+添加职责信息</Button>
          )}
        </div>
      </div>
    );
  }

  private handleDelete(_record: OrgDataItem, index: number) {
    const dataSource = [...this.state.dataSource];
    dataSource.splice(index, 1);
    this.setState({ dataSource }, this.triggerChange);
  }

  private handleAdd(_record: OrgDataItem | null, index: number) {
    const dataSource = [...this.state.dataSource];
    dataSource.splice(index + 1, 0, {
      id: `-${Date.now()}`,
      department: -1,
      description: '',
    });
    this.setState({ dataSource }, this.triggerChange);
  }

  private triggerChange() {
    const { onChange } = this.props;
    const { dataSource } = this.state;
    onChange?.(dataSource);
  }

  private getDataSource = (dataSource: OrgDataItem[] = []) => {
    return dataSource.map((item) => {
      return item;
    });
  };

  private handleDescChange(_record: OrgDataItem, index: number, value: string) {
    this.setState(
      (prevState) => ({
        dataSource: prevState.dataSource.map((v, i) => (i === index ? { ...v, description: value } : { ...v })),
      }),
      this.triggerChange
    );
  }

  private async loadData() {
    this.setState({ loading: true });
    try {
      const { msg, data, code } = await getDepartList();
      if (code === -1) {
        this.setState({
          loading: false,
        });
        message.error(msg);
        return;
      }
      this.setState({
        loading: false,
        departList: data,
      });
    } catch (e) {
      console.error(e);
      message.error('获取人员组组织信息失败');
      this.setState({ loading: false });
    }
  }

  private handleDepartChange(_record: OrgDataItem, index: number, value: number) {
    this.setState(
      (prevState) => ({
        dataSource: prevState.dataSource.map((v, i) => (i === index ? { ...v, department: value } : { ...v })),
      }),
      this.triggerChange
    );
  }
}

export default OrgTable;
